package cn.yuanqiao.web.controller.manage;

import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.poi.ExcelUtil;
import cn.yuanqiao.common.core.controller.BaseController;
import cn.yuanqiao.common.core.domain.AjaxResult;
import cn.yuanqiao.common.core.page.TableDataInfo;
import cn.yuanqiao.common.annotation.Log;
import cn.yuanqiao.common.enums.BusinessType;
import cn.yuanqiao.manage.domain.YqFields;
import cn.yuanqiao.manage.domain.YqdaMdataList;
import cn.yuanqiao.manage.domain.YqdaRelevance;
import cn.yuanqiao.manage.service.IYqdaMdataListService;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 元数据明细Controller
 * 
 * @author yuanqiao
 * @date 2023-06-09
 */
@RestController
@RequestMapping("/manage/mdataList")
public class YqdaMdataListController extends BaseController
{
    @Autowired
    private IYqdaMdataListService yqdaMdataListService;
    @Value("${keep.mdataList-X}")
    private String mdataList_x;
    @Value("${keep.mdataList-V}")
    private String mdataList_v;
    @Value("${keep.mdataList-F}")
    private String mdataList_f;
    @Value("${keep.mdataList-E}")
    private String mdataList_e;

    /**
     * 不可修改字段
     * @return
     */
    @GetMapping(value = "/keepMdataList")
    public AjaxResult keepMdataList()
    {
        JSONObject object = new JSONObject();
        object.put("mdataList_x",mdataList_x.split(","));
        object.put("mdataList_v",mdataList_v.split(","));
        object.put("mdataList_f",mdataList_f.split(","));
        object.put("mdataList_e",mdataList_e.split(","));
        return success(object);
    }

    /**
     * 查询元数据明细列表
     */
    //@PreAuthorize("@ss.hasPermi('manage:YqdaMdataList:list")
    @Log(title = "查询元数据明细列表", businessType = BusinessType.SELECT)
    @GetMapping("/list")
    public TableDataInfo list(YqdaMdataList yqdaMdataList)
    {
        startPage();
        List<YqdaMdataList> list = yqdaMdataListService.selectYqdaMdataListList(yqdaMdataList);
        return getDataTable(list);
    }

    /**
     * 查询全部不带分页
     * @param yqdaMdataList
     * @return
     */
    @GetMapping("/listAll")
    public AjaxResult listAll(YqdaMdataList yqdaMdataList)
    {
        List<YqdaMdataList> list = yqdaMdataListService.selectYqdaMdataListList(yqdaMdataList);
        return AjaxResult.success(list);
    }

    /**
     * 导出元数据明细列表
     */
    //@PreAuthorize("@ss.hasPermi('manage:YqdaMdataList:export")
    @Log(title = "元数据明细", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, @RequestParam("groupId")Long groupId,@RequestParam("type")Integer type,@RequestParam(required = false,value = "fieldName")String fieldName,@RequestParam(required = false,value = "ids")List ids)
    {
        if(groupId == null){
            throw new ServiceException("参数错误");
        }
        List<YqdaMdataList> list = yqdaMdataListService.selectYqdaMdataListListforexport(groupId,type,fieldName,ids);
        ExcelUtil<YqdaMdataList> util = new ExcelUtil<YqdaMdataList>(YqdaMdataList.class);
        util.exportExcel(response, list, "元数据明细数据");
    }

    /**
     * 获取元数据明细详细信息
     */
    //@PreAuthorize("@ss.hasPermi('manage:YqdaMdataList:query")
    @Log(title = "获取元数据明细详细信息", businessType = BusinessType.SELECT)
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(yqdaMdataListService.selectYqdaMdataListById(id));
    }

    //@PreAuthorize("@ss.hasPermi('manage:YqdaMdataList:add")
    @Log(title = "元数据明细", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestParam String ids, @RequestParam Long groupId)
    {
        if(StringUtils.isEmpty(ids) || StringUtils.isNull(groupId)){
            return AjaxResult.error("请检查出入参数");
        }else {
            return toAjax(yqdaMdataListService.insertYqdaMdataList(ids,groupId));
        }
    }

    /**
     * 修改元数据明细
     */
    //@PreAuthorize("@ss.hasPermi('manage:YqdaMdataList:edit")
    @Log(title = "元数据明细", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody YqdaMdataList yqdaMdataList)
    {
        if(StringUtils.isNull(yqdaMdataList.getIds())){
            return AjaxResult.error("请检查输入参数！");
        }else {
            return toAjax(yqdaMdataListService.updateYqdaMdataList(yqdaMdataList,yqdaMdataList.getIds()));
        }
    }
    @Log(title = "元数据明细批量修改", businessType = BusinessType.UPDATE)
    @PutMapping("batch")
    public AjaxResult batchEdit(@RequestBody YqdaMdataList yqdaMdataList)
    {
        if(StringUtils.isNull(yqdaMdataList.getIds())){
            return AjaxResult.error("请检查输入参数！");
        }else {
            return toAjax(yqdaMdataListService.batchUpdateYqdaMdataList(yqdaMdataList,yqdaMdataList.getIds()));
        }
    }

    /**
     * 删除元数据明细
     */
    //@PreAuthorize("@ss.hasPermi('manage:YqdaMdataList:remove")
    @Log(title = "元数据明细", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(yqdaMdataListService.deleteYqdaMdataListByIds(ids));
    }

    /**
     * 根据元数据ID查询基础数据
     *  @RequestParam Long groupId, @RequestParam String type, @RequestParam String fieldCaption, @RequestParam String fieldName
     */
    @Log(title = "根据元数据ID查询基础数据", businessType = BusinessType.SELECT)
    @PostMapping("/listByGroupId")
    public TableDataInfo getGroupDataList(@RequestParam Long groupId, @RequestParam String type, @RequestParam String fieldCaption, @RequestParam String fieldName){
        if(StringUtils.isNull(groupId) || StringUtils.isEmpty(type)){
            throw new ServiceException("参数错误！");
        }
        startPage();
        YqFields yqfields = new YqFields();
        yqfields.setType(type);
        yqfields.setFieldCaption(fieldCaption);
        yqfields.setFieldName(fieldName);
        List<YqFields> getGroupDataList = yqdaMdataListService.getGroupDataList(yqfields,groupId);
        return getDataTable(getGroupDataList);
    }

    /**
     * 查询已勾选元数据项列表
     * @param groupId
     * @return
     */
    @Log(title = "查询已勾选元数据项列表", businessType = BusinessType.SELECT)
    @GetMapping("/getHddaMDataListByIsMetadata")
    public AjaxResult getHddaMDataListByIsMetadata(@RequestParam Long groupId){
        if(StringUtils.isNull(groupId)){
            return AjaxResult.error("参数错误！");
        }
        YqdaMdataList mDataList = new YqdaMdataList();
        mDataList.setGroupId(groupId);
        mDataList.setIsMetadata(1);
        return AjaxResult.success(yqdaMdataListService.selectYqdaMdataListList(mDataList));
    }

    /**
     * 复制元数据项验证验证复制到的元数据方案中是否有重复
     * @param groupId
     * @return
     */
    @Log(title = "元数据方案中是否有重复", businessType = BusinessType.SELECT)
    @GetMapping("/copyIsRepeat")
    public AjaxResult copyIsRepeat(@RequestParam String ids, @RequestParam Long groupId, @RequestParam Integer type){
        if(StringUtils.isEmpty(ids) || StringUtils.isNull(groupId) || StringUtils.isNull(type)){
            return AjaxResult.error("参数错误！");
        }
        String msg = yqdaMdataListService.copyIsRepeat(ids,groupId,type);
        if(StringUtils.isEmpty(msg)){
            return AjaxResult.success("200");
        }else {
            return AjaxResult.success("重复项有："+msg+"，请选择覆盖或者跳过？");
        }
    }

    /**
     * 复制到
     * type = 1 覆盖原来明细 type = 2 跳过
     * @return
     */
    @Log(title = "复制到元数据方案中", businessType = BusinessType.INSERT)
    @PostMapping("/copyToGroup")
    public AjaxResult copyToGroup(@RequestParam String ids, @RequestParam Long groupId, @RequestParam String type){
        if(StringUtils.isEmpty(ids) || StringUtils.isNull(groupId)){
            return AjaxResult.error("参数错误！");
        }
        yqdaMdataListService.copyToGroup(ids,groupId,StringUtils.isNotEmpty(type) ? Integer.valueOf(type):null);
        return AjaxResult.success();
    }

    /**
     * 元数据明细导入
     * @param file
     * @param groupId
     * @param type
     * @return
     * @throws Exception
     */
    @Log(title = "元数据明细导入", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, Long groupId, Integer type) throws Exception
    {
        if(file.isEmpty() || StringUtils.isNull(groupId) || StringUtils.isNull(type)){
            return AjaxResult.error("参数错误！");
        }
        ExcelUtil<YqdaMdataList> util = new ExcelUtil<>(YqdaMdataList.class);
        List<YqdaMdataList> dataLists = util.importExcel(file.getInputStream());
        yqdaMdataListService.importHddaMDataList(dataLists,groupId,type);
        return AjaxResult.success();
    }

    /**
     * 导出元数据方案明细模板
     * @param response
     * @throws IOException
     */
    @Log(title = "导出元数据方案明细模板", businessType = BusinessType.EXPORT)
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException
    {
        ExcelUtil<YqdaMdataList> util = new ExcelUtil<YqdaMdataList>(YqdaMdataList.class);
        util.importTemplateExcel(response, "元数据明细");
    }
    /**
     * 查询元数据明细列表
     */
    //@PreAuthorize("@ss.hasPermi('manage:YqdaMdataList:list")
    @Log(title = "查询三合一元数据明细列表", businessType = BusinessType.SELECT)
    @PostMapping("/listforshy")
    public TableDataInfo listforshy(@RequestBody JSONObject json)
    {
        startPage();
        Long groupId=json.getLong("groupId");
        Integer type=json.getInteger("type");
        String fieldCaption=json.getString("fieldCaption");
        String fieldName=json.getString("fieldName");
        Long categoryId= json.getLong("categoryId");
        List<Map<String,Object>> list = yqdaMdataListService.selectYqdaMdataListListforshy(groupId,type,fieldCaption,fieldName,categoryId);
        return getDataTable(list);
    }


    @Log(title = "添加三合一元数据明细", businessType = BusinessType.UPDATE)
    @PostMapping("/addmdatatoshy")
    public AjaxResult addmdatatoshy(@RequestBody JSONObject json)
    {
        JSONArray ids=json.getJSONArray("ids");
        Integer type=json.getInteger("type");
        Long categoryId= json.getLong("categoryId");
        Long groupId=json.getLong("groupId");
        Integer count = yqdaMdataListService.addmdatatoshy(ids,type,categoryId,groupId);
        return AjaxResult.success(count);
    }
    @Log(title = "删除三合一元数据明细", businessType = BusinessType.DELETE)
    @PostMapping("/deletemdatafromshy")
    public AjaxResult deletemdatafromshy(@RequestBody JSONObject json)
    {
        JSONArray ids=json.getJSONArray("ids");
        Integer type=json.getInteger("type");
        Long categoryId= json.getLong("categoryId");
        Long groupId=json.getLong("groupId");
        Integer count = yqdaMdataListService.deletemdatafromshy(ids,type,categoryId,groupId);
        return AjaxResult.success(count);
    }
    @Log(title = "获取关联列表",businessType = BusinessType.SELECT)
    /** 获取关联列表 */
    @PostMapping("/getrelevancelist")
    public TableDataInfo getrelevancelist(@RequestBody JSONObject json)
    {
        List<YqdaRelevance> list=yqdaMdataListService.getrelevancelist(json);
        return getDataTable(list);
    }
    /** 获取关联字段
     * 只获取下一层,项目->卷/卷->件
     * @params field 当前字段
     * @params nowlevel  当前层级
     * @params relelevel  关联字段的层级
     * @params fieldtype  当前字段类型
     * @params groupId 当前的元数据方案id
     * */
    @Log(title = "获取关联字段",businessType = BusinessType.SELECT)
    @PostMapping("/getrelevancefield")
    public AjaxResult getrelevancefield(@RequestBody JSONObject json)
    {
        List<Map<String,Object>> list = yqdaMdataListService.getrelevancefield(json);
        return success(list);
    }

    /** 添加关联
     * @params field 当前字段
     * @params relefield 关联字段
     * @params nowlevel  当前层级
     * @params relelevel  关联字段的层级
     * @params fieldtype  当前字段类型
     * @params relefieldtype  关联字段类型
     * @params relation 关联
     * @params groupId 当前的元数据方案id
     * */
    @Log(title = "添加关联",businessType = BusinessType.INSERT)
    @PostMapping("/addrelevance")
    public AjaxResult addrelevance(@RequestBody JSONObject json)
    {
        int i = yqdaMdataListService.addrelevance(json);
        return success(i);
    }

    @Log(title = "获取关联明细",businessType = BusinessType.INSERT)
    @PostMapping("/getreledetail/{id}")
    public AjaxResult getreledetail(@PathVariable("id")Long id)
    {
        YqdaRelevance relevance = yqdaMdataListService.getreledetail(id);
        return success(relevance);
    }
    @Log(title = "修改关联",businessType = BusinessType.UPDATE)
    @PostMapping("/editrele")
    public AjaxResult editrele(@RequestBody YqdaRelevance relevance)
    {
        int i = yqdaMdataListService.editrele(relevance);
        return success(i);
    }
    @Log(title = "删除关联",businessType = BusinessType.DELETE)
    @PostMapping("/delterele")
    public AjaxResult delterele(@RequestBody JSONObject json)
    {
        int i = yqdaMdataListService.delterele(json);
        return success(i);
    }
    @Log(title = "下移元数据排序",businessType = BusinessType.UPDATE)
    @PostMapping("/moveDown")
    public AjaxResult moveDown(@RequestBody JSONObject json)
    {
        return success(yqdaMdataListService.moveDown(json.getLong("metadataListIds"),json.getLong("groupId"),json.getLong("categoryId"),json.getInteger("type")));

    }
    @Log(title = "上移元数据排序",businessType = BusinessType.UPDATE)
    @PostMapping("/moveUp")
    public AjaxResult moveUp(@RequestBody JSONObject json)
    {
        return success(yqdaMdataListService.moveUp(json.getLong("metadataListIds"),json.getLong("groupId"),json.getLong("categoryId"),json.getInteger("type")));

    }
}
